package cn.zxy.config;


import cn.zxy.exception.BizException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Component
//第二种方式
//它是通过实现HandlerExceptionResolver接口，进行一个全局异常处理
//好处：不需要在每一个controller种编写自己的异常方法
public class MyExceptionResolver implements HandlerExceptionResolver {

//    @ExceptionHandler(BizException.class)
//    public ModelAndView error(BizException ex){
//        ModelAndView mv = new ModelAndView();
//        mv.addObject("msg",ex.getCode()+"==>"+ex.toString());
//        mv.setViewName("biz");
//        return mv;
//    }

    @Override
    public ModelAndView resolveException(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler, Exception ex) {

        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",ex.getMessage());
        if (ex instanceof NullPointerException){
            mv.setViewName("nullPoint");
        } else if (ex instanceof ArithmeticException) {
            mv.setViewName("arith");
        }else {
            mv.setViewName("error");
        }


        //1. 第一次
//        ModelAndView mv = new ModelAndView("error");
//        mv.addObject("msg",ex.getMessage());

        return mv;
    }
}
